// 表格和分页部分
import { Table, Pagination, TableProps } from '@kedacom/react-next'
import React, { useEffect, useState } from 'react'
interface ViewProps<T = any> extends TableProps<T> {
	tableDataList: T[]
	rowKey?: string
	pager?: pagerProps
	onPageChange?: Function
	needCheckbox?: boolean
}
export interface pagerProps {
	page: number
	size?: number
	total?: number
}
export const defaultPage = {
	page: 1, //当前页
	size: 15, //每一页的条目
	total: 0,
}
interface UseHookProps {
	pager?: pagerProps
	onPageChange?: Function
}
const useHook = ({ pager, onPageChange }: UseHookProps) => {
	const [tablePager, setTablePager] = useState({
		...defaultPage,
		...pager,
	})

	useEffect(() => {
		setTablePager({
			...tablePager,
			...pager,
		})
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [pager])
	//页码改变时重新加载
	const onHandlePageChange = (pageIndex: number = 0, pageSize: number) => {
		onPageChange && onPageChange(pageIndex, pageSize)
	}
	return {
		tablePager,
		onHandlePageChange,
	}
}
const TableView = ({
	tableDataList,
	columns,
	onRowSelect,
	onRowSelectAll,
	pager,
	onRowClick,
	onPageChange,
	...props
}: ViewProps) => {
	const { ..._useHook } = useHook({ pager, onPageChange })
	const tablePager = _useHook.tablePager
	const start = (tablePager.page - 1) * tablePager.size + 1
	return (
		<>
			<Table
				showSelectColumn={props.needCheckbox}
				data={tableDataList}
				columns={columns}
				rowIdField={props.rowKey || 'id'}
				onRowSelect={onRowSelect && onRowSelect}
				onRowSelectAll={onRowSelectAll && onRowSelectAll}
				onRowClick={onRowClick && onRowClick}
				orderStartNumber={start}
			/>
			{pager && (
				<div className="page-wrap">
					<Pagination
						isDisplayMsg={true}
						onChange={(e, pageIndex) => _useHook.onHandlePageChange(pageIndex, _useHook.tablePager.size)}
						total={_useHook.tablePager.total}
						current={_useHook.tablePager.page}
						pageSize={_useHook.tablePager.size}
					/>
				</div>
			)}
		</>
	)
}

export default TableView
